import {Logger} from "./Logger";
import fs from "fs";

export function logNowTime(tag?: string) {
    if (!Logger.debug) {
        return
    }
    const date = new Date();
    const options: Intl.DateTimeFormatOptions = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric',
    };
    const currentDate = date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric',
    });
    if (tag === undefined || tag === null || tag === '') {
        Logger.info("", "end time:" + currentDate)
    } else {
        Logger.info(tag, "end time:" + currentDate)
    }
}

export function deleteExcessCommas2(input: string): string {
    // const regex = /\,(?!\s*?[\{\[\"\'\w\_])/g;
    //或者
    const regex = /\,(?=\s*?[\}\]])/g;
    const json: string = input.replace(regex, '');
    return json
}
export function deleteExcessCommas(jsonString: string): string {
    // 匹配末尾逗号（前面可能有空格）后接 } 或 ]
    const regex = /,(\s*)([}\]])/g;
    // 替换为保留空格和结束符号，去掉逗号
    return jsonString.replace(regex, '$1$2');
}

export function readFileContent(filePath: string): string {
    try {
        let data = fs.readFileSync(filePath, {encoding: "utf-8"});
        return data
    } catch (err) {
        return ""
    }
}

export function removeComments2(code: string): string {
    // 匹配单行注释和多行注释的正则表达式
    const commentRegex = /\/\/.*|\/\*[\s\S]*?\*\//g;

    // 替换注释为空字符串，并处理可能的遗留空格
    return code.replace(commentRegex, (match) => {
        // 保留换行符以避免代码合并
        return match.includes('\n') ? '\n' : '';
    }).replace(/^\s*[\r\n]/gm, ''); // 清理空行
}
export function removeComments(code: string): string {
    const regex = /((["'`])(?:\\.|[\s\S])*?\2)|\/\/.*|\/\*[\s\S]*?\*\//g;

    return code.replace(regex, (match, str) => {
        // 保留字符串内容
        if (str) return str;

        // 处理注释（保留换行符）
        const lines = match.split('\n').length;
        return lines > 1 ? '\n'.repeat(lines - 1) : '';
    })
}